package com.tolerate.managespringboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tolerate.managespringboot.common.Result;
import com.tolerate.managespringboot.entity.Role;
import com.tolerate.managespringboot.entity.User;
import com.tolerate.managespringboot.mapper.RoleMapper;
import com.tolerate.managespringboot.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Role role) {
        if (role.getId() == null) {
            roleService.save(role);
        } else {
            roleService.updateById(role);
        }
        return Result.success();
    }


    @GetMapping("/page")
    public Result page(Integer pageNum, Integer pageSize, String name, String description) {
        IPage<Role> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 使用条件构造查询，避免当参数为空时执行不必要的like操作
        if (name != null && !name.trim().isEmpty()) {
            lambdaQueryWrapper.like(Role::getName, name.trim());
        }
        if (description != null && !description.trim().isEmpty()) {
            lambdaQueryWrapper.like(Role::getDescription, description.trim());
        }

        IPage<Role> roleIPage = roleService.page(page, lambdaQueryWrapper);

        // 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("data", roleIPage.getRecords());
        map.put("total", roleIPage.getTotal());
        return Result.success(map);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean b = roleService.removeById(id);
        return Result.success();
    }

    @PostMapping("/delBatch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        boolean b = roleService.removeByIds(ids);
        return Result.success();
    }

    // 获取全部数据
    @GetMapping("/list")
    public Result list() {
        List<Role> list = roleMapper.selectList(null);
        return Result.success(list);
    }
}
